package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.ArticleFreemarkerService;
import com.heima.common.constants.ArticleConstants;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.search.vos.SearchArticleVo;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
@Transactional
public class ArticleFreemarkerServiceImpl implements ArticleFreemarkerService {
    @Autowired
    private Configuration configuration;
    @Autowired
    private ApArticleContentMapper apArticleContentMapper;
    @Autowired
    private FileStorageService fileStorageService;
    /**
     * 生成静态文件上传到minIO中
     *
     * @param article
     * @param content
     */
    @Async
    @Override
    public void buildArticleToMinIO(ApArticle article, String content) {
        if (StringUtils.isBlank(content)){
            return;
        }
        // 1. 生成静态html文件
        try {
            Template template = configuration.getTemplate("article.ftl");
            Map map = new HashMap<>();
            map.put("title",article.getTitle());
            map.put("content", JSONArray.parseArray(content));
            StringWriter out = new StringWriter();
            template.process(map,out);
            // 2. 上传到minio
            String staticUrl = fileStorageService.uploadHtmlFile(
                    "",
                    article.getId() + ".html",
                    new ByteArrayInputStream(out.toString().getBytes())
            );
            // 3. 修改ap_article表，将minio中的文件路径写入到表中
            article.setStaticUrl(staticUrl);
            apArticleService.updateById(article);
            // 4. 通过kafka发送消息，通知search微服务创建文章的文档
            createArticleESIndex(article,content);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    /**
     * 通过kafka发送消息，通知search微服务创建文章的文档
     * @param article
     * @param content
     */
    private void createArticleESIndex(ApArticle article, String content) {
        SearchArticleVo searchArticleVo = new SearchArticleVo();
        BeanUtils.copyProperties(article, searchArticleVo);
        searchArticleVo.setContent(content);
        kafkaTemplate.send(ArticleConstants.TOPIC_ARTICLE_ES_SYNC, JSON.toJSONString(searchArticleVo));
    }

    @Autowired
    private ApArticleService apArticleService;
}
